package com.snails.app.utils;

import android.view.View;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * 点击防抖
 *
 * @author lawrence
 * @date 2019-05-06 15:06
 */
public class DoubleClickHelper {
    private static final int windowDuration = 1;

    public static void click(View view, Runnable r) {
        click(view, r, windowDuration);
    }

    public static void click(View view, Runnable r, int durationSeconds) {
        if (view == null || r == null) {
            return;
        }
        Observable.create(new ClickObservable(view)).throttleFirst(durationSeconds, TimeUnit.SECONDS).subscribe(o -> r.run());
    }

    public static void click(View view, View.OnClickListener listener) {
        click(view, listener, windowDuration);
    }

    public static void click(View view, View.OnClickListener listener, int durationSeconds) {
        if (view == null || listener == null) {
            return;
        }
        Observable.create(new ClickObservable(view)).throttleFirst(durationSeconds, TimeUnit.SECONDS).subscribe(o -> listener.onClick(view));
    }

    private DoubleClickHelper() {
    }

    public static class ClickObservable implements ObservableOnSubscribe<View> {
        private ObservableEmitter mEmitter;

        public ClickObservable(View view) {
            view.setOnClickListener(v -> {
                if (mEmitter != null) mEmitter.onNext(v);
            });
        }

        @Override
        public void subscribe(ObservableEmitter<View> e) throws Exception {
            mEmitter = e;
        }
    }
}
